import pymysql
import threading
lock = threading.Lock()


class DB:
    # 初始化方法
    def __init__(self) -> None:
        self.conn = pymysql.connect(host='localhost',port=3306,db='syl',
        charset='utf8',user='root',password="123",cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()
    # 处理并发问题
    def reConnect(self):
        try:
            self.conn.ping()
        except:
            self.conn()

    #添加修改
    def add(self,sql):
        self.cursor.execute(sql)
        return self.cursor.lastrowid

    #获取单条
    def findone(self,sql):
        lock.acquire()
        self.reConnect()
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        lock.release()
        return res
    #获取多条
    def findAll(self,sql):
        lock.acquire()
        self.reConnect()
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        lock.release()
        return res
    #关闭
    def close(self):
        self.cursor.close()
        self.conn.close()
    # 提交
    def commit(self):
        self.conn.commit()
    # 事务回滚
    def rollback(self):
        self.conn.rollback()
db = DB()



